package tr.muyat.sensorlist;

import java.util.List;

import android.app.ListActivity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MyListActivity extends ListActivity implements SensorEventListener {

	private List<Sensor> sensorList;
	SensorManager sensorManager;
	private long lastUpdate;
	private boolean color = false;
	private int sensorType = Sensor.TYPE_ALL;

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);

		String[] sensorNames = new String[sensorList.size()];
		for (int i = 0; i < sensorNames.length; i++) {
			sensorNames[i] = sensorList.get(i).getName();
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, sensorNames);
		setListAdapter(adapter);

		sensorManager.registerListener(this,
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER ),
				SensorManager.SENSOR_DELAY_GAME);
		lastUpdate = System.currentTimeMillis();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// String item = (String) getListAdapter().getItem(position);
		String item = sensorList.get(position).getVendor();
		//Toast.makeText(this, "Vendor: " + item, Toast.LENGTH_SHORT).show();
		sensorType = sensorList.get(position).getType();

	}

	public void onSensorChanged(SensorEvent event) {

//		if ((event.sensor.getType() == Sensor.TYPE_LIGHT)) {
//			float[] values = event.values;
//			float light = values[0];
//			Toast.makeText(this, "Light=" + light, Toast.LENGTH_SHORT).show();
//		} else
		if ((event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)) {
			float[] values = event.values;
			// Movement
			float x = values[0];
			float y = values[1];
			float z = values[2];

			float accelationSquareRoot = (x * x + y * y + z * z)
					/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
			long actualTime = System.currentTimeMillis();
			if (accelationSquareRoot >= 1) //
			{
				if (actualTime - lastUpdate < 200) {
					return;
				}
				lastUpdate = actualTime;
				Toast.makeText(this, "x=" + x + ", y=" + y + ", z=" + z,
						Toast.LENGTH_SHORT).show();
				color = !color;
			}

		}

	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}
}